/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.wiki;

import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Module;
import fitnesse.wiki.WikiPage;
import fitnesse.wikitext.WidgetBuilder;
import fitnesse.wikitext.WidgetInterceptor;
import fitnesse.wikitext.WikiWidget;
import fitnesse.wikitext.widgets.WidgetRoot;
import org.xptracker.domain.Domain;
import org.xptracker.domain.NamedMap;
import org.xptracker.persistence.PersistenceListener;
import org.xptracker.persistence.PersistenceManager;
import org.xptracker.test.IntegrationTest;

import java.util.List;

public class ExternalLinkWidgetTest extends IntegrationTest {
  private XpFitWidgetBuilder builder;

  protected void beforeInjection(List<Module> modules, List<PersistenceListener> listeners) {
    builder = new XpFitWidgetBuilder();
    modules.add(new AbstractModule() {
      protected void configure() {
        bind(WidgetBuilder.class).toInstance(builder);
      }
    });
  }

  protected void afterInjection(final Injector injector) {
    builder.addInterceptor(new WidgetInterceptor() {
      public void intercept(WikiWidget wikiWidget) throws Exception {
        injector.injectMembers(wikiWidget);
      }
    });
  }

  public void testCustomWidget() throws Exception {
    mgr.inTransaction(new PersistenceManager.UpdateHandler<Object>() {
      public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
        NamedMap map = new Domain(mgr).getNamedMap(receiver, ExternalLinkWidget.CUSTOM_LINKS);
        map.map.put("test", "this is bob''s favorite link: {0}");
        receiver.update(map);
        return null;
      }
    });

    WidgetRoot root = new WidgetRoot("test:george-bob-1.5 is fun" + "\n", (WikiPage) null, builder);
    String output = root.render();
    assertEquals("<a class=\"ext-link\" href=\"this is bob's favorite link: george-bob-1.5\">test: george-bob-1.5</a> is fun<br>", output);
    root = new WidgetRoot("ext:test:george-bob-1.5 is fun" + "\n", (WikiPage) null, builder);
    output = root.render();
    assertEquals("<a class=\"ext-link\" href=\"this is bob's favorite link: george-bob-1.5\">test: george-bob-1.5</a> is fun<br>", output);
  }
}
